<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!--<el-form-item label="名称" prop="cycleFee">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="是否启用" prop="enable">
        <el-select v-model="queryParams.enable" class="labelWidth" filterable placeholder="请选择状态">
          <el-option
            key="1"
            label="启用"
            value="1">
          </el-option>
          <el-option
            key="0"
            label="禁用"
            value="0">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:price:add']"
        >新增
        </el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:price:export']"
        >导出
        </el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="priceList" @selection-change="handleSelectionChange">
      <el-table-column label="规则ID" align="center" prop="id"/>
      <el-table-column label="名称" align="center" prop="name">
        <template slot-scope="scope">
          {{scope.row.name || '暂无'}}
        </template>
      </el-table-column>
      <el-table-column label="计费周期(分钟)" align="center" prop="cycleOfMinute"/>
      <el-table-column label="免费时长(分钟)" align="center" prop="freeTime"/>
      <el-table-column label="周期费用(元)" align="center" prop="cycleFeeShow"/>
      <el-table-column label="最高费用(元)" align="center" prop="maxFeeShow"/>
      <el-table-column label="是否启用" align="center" prop="enable">
        <template slot-scope="scope">
          <el-tag :type="scope.row.enable == 1 ? 'success' : ''">
            {{ scope.row.enable == 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="默认标记" align="center" prop="createType">
        <template slot-scope="scope">
          <el-tag :type="scope.row.createType == 1 ? '' : 'warning'">
            {{ scope.row.createType == 1 ? '默认' : '创建' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-lock"
            @click="handleBind(scope.row)"
            v-hasPermi="['business:price:edit']"
          >绑定车位
          </el-button>
          <el-button
            v-if="scope.row.createType == 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:price:edit']"
          >修改
          </el-button>
          <el-button
            v-if="scope.row.createType == 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:price:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改占位计费规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="135px">
        <el-form-item label="计费名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="计费周期(分钟)" prop="cycleOfMinute" type="number">
          <el-input v-model="form.cycleOfMinute" placeholder="请输入计费周期"/>
        </el-form-item>
        <el-form-item label="免费时长(分钟)" prop="freeTime" type="number">
          <el-input v-model="form.freeTime" placeholder="请输入免费时长"/>
        </el-form-item>
        <el-form-item label="周期费用(元)" prop="cycleFee" type="number">
          <el-input v-model="form.cycleFee" placeholder="请输入周期费用" precision="2"/>
        </el-form-item>
        <el-form-item label="单次最高费用(元)" prop="maxFee" type="number">
          <el-input v-model="form.maxFee" placeholder="请输入单次最高费用" precision="2"/>
        </el-form-item>
        <el-form-item label="是否启用" prop="enable">
          <el-select v-model="form.enable" class="labelWidth" filterable placeholder="请选择状态">
            <el-option
              key="1"
              label="启用"
              :value="1">
            </el-option>
            <el-option
              key="0"
              label="禁用"
              :value="0">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 绑定车位 -->
    <el-dialog
      :title="title"
      :visible.sync="openBind"
      width="1200px"
      append-to-body>
      <el-row :gutter="24">
        <el-col
          :span="10"
          :xs="24">
          <div style="padding-bottom: 10px">占位规则</div>
          <el-descriptions :column="1" border class="margin-top" title="">
            <el-descriptions-item>
              <template slot="label">
                规则ID
              </template>
              {{timeList.id}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                计费名称
              </template>
              {{timeList.name || '暂无'}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                计费周期(分钟)
              </template>
              {{timeList.cycleOfMinute}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                免费时长(分钟)
              </template>
              {{timeList.freeTime}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                周期费用(元)
              </template>
              {{timeList.cycleFeeShow}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                最高收费(元)
              </template>
              {{timeList.maxFeeShow}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                是否启用
              </template>
              <el-tag :type="timeList.enable == 1 ? 'success' : ''">
                {{ timeList.enable == 1 ? '启用' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col
          :span="14"
          :xs="24">
          <div style="padding-bottom: 5px">选择车位</div>
          <div>
            <el-tree
              style="height: 315px; overflow: auto"
              class="tree-border"
              default-expand-all
              :data="deviceOptions"
              show-checkbox
              ref="device"
              node-key="id"
              :default-checked-keys="checkedkeys"
              :check-strictly="false"
              empty-text="加载中，请稍候"
              :props="defaultProps"
            ></el-tree>
          </div>
        </el-col>
      </el-row>
      <div
        slot="footer"
        class="dialog-footer">
        <el-button
          type="primary"
          @click="submitBind">确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listPrice, getPrice, delPrice, addPrice, updatePrice, getDeviceAll, saveParkingPrice} from "@/api/business/price";
import { listModel, getModel, delModel, addModel, updateModel, getDeviceType, getAllDevice, bindModel , getProtocolList } from '@/api/business/model'
import { ChangeHourMinutestr, ChangeStrToMinutes } from '@/utils/common'

export default {
  name: "Price",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 占位计费规则表格数据
      priceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        cycleFee: null,
        cycleOfMinute: null,
        enable: null,
        maxFee: null,
        createType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {

        cycleOfMinute: [
          { required: true, message: "计费周期不能为空", trigger: "blur" },
          {
            validator(rule, value, callback) {
              if (Number.isInteger(Number(value)) && Number(value) > 0 && Number(value) < 99999999) {
                callback()
              } else {
                callback(new Error('请输入正确的正整数'))
              }
            },
            trigger: 'blur'
          }
        ],
        freeTime: [
          { required: true, message: "免费时长不能为空", trigger: "blur" },
          {
            validator(rule, value, callback) {
              if (Number.isInteger(Number(value)) && Number(value) > 0 && Number(value) < 99999999) {
                callback()
              } else {
                callback(new Error('请输入正确的正整数'))
              }
            },
            trigger: 'blur'
          }
        ],
        cycleFee: [
          { required: true, message: "周期费用不能为空", trigger: "blur" },
          { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入正确的格式,可保留两位小数' }
        ],
        maxFee: [
          { required: true, message: "单次最高费用不能为空", trigger: "blur" },
          { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入正确的格式,可保留两位小数' }
        ],
      },
      openBind: false,
      modelId: '',
      checkedkeys: [],
      deviceOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      timeList: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询占位计费规则列表 */
    getList() {
      this.loading = true;
      listPrice(this.queryParams).then(response => {
        this.priceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openBind = false
      this.timeList = {}
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        freeTime: null,
        cycleFee: null,
        cycleOfMinute: null,
        enable: 1,
        maxFee: null,
        createType: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加占位计费规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPrice(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改占位计费规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePrice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            delete this.form.id
            addPrice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除占位计费规则编号为"' + ids + '"的数据项？').then(function () {
        return delPrice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/price/export', {
        ...this.queryParams
      }, `price_${new Date().getTime()}.xlsx`)
    },
    handleBind(row) {
      this.checkedkeys = []
      this.title = '车位绑定'
      this.timeList = row
      this.modelId = row.id
      getDeviceAll().then(res => {
        this.openBind = true
        let refArray = res.data.map((obj, key) => {
          if(obj.parkinglocks.length>0) {
            obj.parkinglocks.forEach(item=>{
              if(row.id == item.priceId) {
                this.checkedkeys.push(item.macid)
              }
            })
          }
          let rObj = {}
          rObj.id = obj.macid
          rObj.label = obj.stationName
          if (obj.parkinglocks.length > 0) {
            rObj.children = this.getChildren(obj.parkinglocks)
          } else {
            rObj.disabled = true
          }
          return rObj
        })
        this.deviceOptions = refArray
      })
    },
    getChildren (arr) {
      let refArray = arr.map((obj, key) => {
        let rObj = {}
        rObj.id = obj.macid
        rObj.label = obj.parkName + '_' + obj.macid
        return rObj
      })
      return refArray
    },
    submitBind() {
      const bindParams = {}
      let Keys = this.getDeptAllCheckedKeys()
      if (Keys.length == 0) {
        this.$modal.msgError('请选择一个或多个地锁设备')
        return false
      }
      let deviceIds = []
      Keys.forEach(item => {
        if (!item.hasOwnProperty('children')) {
          deviceIds.push(item.id)
        }
      })
      bindParams.parkIngIDs = deviceIds
      bindParams.priceId = this.modelId
      saveParkingPrice(bindParams).then(res => {
        this.$modal.msgSuccess('绑定成功')
        this.openBind = false
      }).catch(err=>{
        this.$modal.msgError(err.msg)
      })
    },
    getDeptAllCheckedKeys () {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.device.getCheckedNodes()
      return checkedKeys
    }
  }
};
</script>
